import logging
from rest_framework import mixins
from rest_framework.viewsets import GenericViewSet
from django_filters.rest_framework import DjangoFilterBackend
from django.conf import settings
from rest_framework.decorators import action
from .serializer import *
from utils.WeiXinPay import WeChatPayPlus
from utils.response import render_json, except_render
from utils.WeiXinUser import WeiXinUser

logger = logging.getLogger('pay')


# Create your views here.
class PayView(GenericViewSet, mixins.ListModelMixin):
    queryset = Order.objects.all()
    serializer_class = OrderSerialzier
    filter_backends = (DjangoFilterBackend,)

    @except_render
    @action(methods=["get"], detail=False, url_path="current_question", url_name="current_question")
    def pay_mini_program(self, request):
        """
        获取当期游戏问题
        """
        data = request.data
        code = data.get('code')
        if not code:
            return render_json(False, None, '数据不正确')
        nick_name = data.get('nick_name')
        if not nick_name:
            return render_json(False, None, '数据不正确')
        wx = WeiXinUser(settings.WX_APP_ID, settings.WX_SECRET)
        result = wx.get_open_id_and_unique_id(code)
        if not result.code:
            return render_json(False, None, '获取用户OpenID或UnionID失败')
        chat_pay = WeChatPayPlus()
        data = chat_pay.pay_mini_program(description='测试说明', trade_no=None, amount=1, open_id='', attach='')
        return render_json(True, data, '')
